import JSEncrypt from "jsencrypt";
/**
 * 此项目使用RSA非对称加密方式
 * 前端保存的是 私钥B  和公钥A
 * 后端保存的是 公钥B  和私钥A
 * 前端将数据使用公钥A加密之后传给后端、后端在通过已有的私有A进行解密
 * 若后端返回的数据需要前端解密 则前端拿本地写死的私钥B 解密 后端通过公钥B加密的数据
 * * */
// 解密
export const decryptRSA = (str: string) => {
  const encryptor = new JSEncrypt(); // 新建JSEncrypt对象
  const privateKey = `-----BEGIN PRIVATE KEY-----
  MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA7l8dnGmHsflINQom
  KtCuY5waKD1uEqoUjKy+6RQa/IRC63xBDtWWwNTDoLiadRs7Qf+D/ibMA8IVuhYA
  M7sIgQIDAQABAkAdy8Xnx0ku9foQpzQeJfeme9zJKuSXcKsg6nbyq5Cz/5aYDA1k
  Jm6XxCjyKSZ+shwa8hanUo1s2eiMUZHESYABAiEA/KDM9GHo6GO5NSP8oF5GKIS0
  3ABP9OWBs6Jtp+J6xcMCIQDxjZohK04Ya4WIyis02BA8VNkbMo0xIwW25ddnomYg
  awIhAIghUjACLpJDYoLbMH9uLZoZ4KeIV42cuqaEyVglN4knAiEAtt9NYO84IKTG
  Y9kq/MbXA9X4x+5tllW9bcp0WbFJQCECIQDgbRG3UgLrD5e7jJQ0n6+L7Mtql1iT
  3tU4hxHPRgjC8Q==
  -----END PRIVATE KEY-----`; // 私钥串
  encryptor.setPrivateKey(privateKey); //设置私钥
  const decrytStr = encryptor.decrypt(str);
  return decrytStr;
};
// 加密
export const encryptRSA = (str: string): string | boolean => {
  const encryptor = new JSEncrypt(); // 新建JSEncrypt对象
  // 此处注意公钥必须合法 否则会加密失败、返回的结果是false
  // http://web.chacuo.net/netrsakeypair 生成合法RSA公钥私钥的网站
  const publicKey = `-----BEGIN PUBLIC KEY-----
  MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAO5fHZxph7H5SDUKJirQrmOcGig9bhKq
  FIysvukUGvyEQut8QQ7VlsDUw6C4mnUbO0H/g/4mzAPCFboWADO7CIECAwEAAQ==
  -----END PUBLIC KEY-----`;
  encryptor.setPublicKey(publicKey); // 设置公钥
  const rsaPassWord = encryptor.encrypt(String(str));
  return rsaPassWord;
};
